import { makeAutoObservable, } from "mobx";
import { showError } from "../components/Message";
import { VideoData, VideoDetail, VideoDetailService, VideoItem, VideoService } from "../services/VideoService";

class VideoStore {
  public list: VideoItem[] = [];
  public loading: boolean = false;
  private _page = 1;
  public loadingMore: boolean = false;
  private noMore: boolean = false;
  public videoDetail?: VideoDetail;
  public selectedItem?: VideoItem;

  constructor() {
    makeAutoObservable(this);
  }

  public async getData(loadmore: boolean = false) {
    if (this.loading || this.loadingMore) {
      return;
    }
    let response: VideoData;

    if (loadmore) {
      if (this.noMore) {
        return;
      }
      this.loadingMore = true;
      this._page += 1;
    } else {
      this.loading = true;
      this._page = 1;
    }
    try {
      response = await new VideoService(this._page).send();
    } catch (e: any) {
      this.loading = false;
      this.loadingMore = false;
      showError(e);
      return;
    }
    this.loading = false;
    this.loadingMore = false;
    if (loadmore) {
      this.noMore = response.list.length === 0;
      this.list.push(...response.list);
    } else {
      this.list = response.list;
    }
  }

  public async getDetail(id: number) {
    if (this.loading || this.loadingMore) {
      return;
    }
    let response: VideoDetail;
    this.loading = true;
    this._page = 1;
    try {
      response = await new VideoDetailService(id).send();
    } catch (e: any) {
      this.loading = false;
      showError(e);
      return;
    }
    this.loading = false;
    this.videoDetail = response;
  }


}

const videoStore = new VideoStore();

export { videoStore };